"""
Poller thread.
"""
__author__ = 'x0r'

import time
from poller import Poller
import threading
from threading import *
from log import Logger
from settings import Settings
import os


class ThreadWorker(threading.Thread):
    def __init__ (self, data_set):
        self.__conf = Settings('magentd.conf')
        self.__logger = Logger(self.__conf.value["log"])
        self.__send_interval = self.__conf.value["sendInterval"]
        self.__data_set = data_set
        self.__terminate = False
        # Init base class
        threading.Thread.__init__(self)
        self.__logger.log("Thread initiated: poller (%s)" %
                          threading.Thread.getName(self)
        )


    def run(self):
        """
        Override parent class method.
        Thread starts here.
        """
        self.p = Poller() # Poller instance

        # Try to open the pipe
        try:
            self.__pipe_r = os.open("magentd.fifo",os.O_RDONLY|os.O_NONBLOCK)
            self.__logger.log("%s: opening communication pipe"%
                              threading.Thread.getName(self)
            )
        except OSError, e:
            self.__logger.log("ERROR: can't open pipe: %s"% e.strerror)
            exit (1)

        self.__logger.log("%s: starting collecting data every %ss"%
                         (threading.Thread.getName(self),
                          self.__send_interval)
        )
        # Infinite loop here
        while True and not self.__terminate:
            self.p.ProcessRequest(self.__data_set)
            time.sleep(float(self.__send_interval))

        print "%s has finished." % self.getName()
        exit(0)

